from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from utils.jwttool import meansjwt
import jwt
from user.models import User


class MyAuthorization(BaseAuthentication):
    def authenticate(self, request):
        token = request.META.get('HTTP_AUTHORIZATION')
        if not token:
            raise AuthenticationFailed('缺少token')
        try:
            user = meansjwt.parseToken(token)
            info = User.objects.filter(id=user['id']).first()
            if not user:
                raise AuthenticationFailed('用户不存在')
            return (info,token)
        except jwt.ExpiredSignatureError:
            raise AuthenticationFailed('token过期')
        except jwt.InvalidTokenError:
            raise AuthenticationFailed('token无效')
